package com.laiketui.admin.mch.service.plugin;

import com.laiketui.admin.mch.api.plugin.BargainService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.data.GoodsDataUtils;
import com.laiketui.common.utils.tool.str.StringUtils;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.order.BargainOrderModel;
import com.laiketui.domain.plugin.bargain.BargainConfigModel;
import com.laiketui.domain.plugin.bargain.BargainRecordModel;
import com.laiketui.domain.product.BargainGoodsModel;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.domain.vo.plugin.bargin.AddBargainGoodsVo;
import com.laiketui.common.api.PubliceService;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.core.utils.tool.DateUtil;
import com.laiketui.core.utils.tool.SerializePhpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 砍价后台管理
 *
 * @author Trick
 * @date 2021/5/13 15:11
 */
@Service
public class BargainServiceImpl implements BargainService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BargainGoodsModelMapper bargainGoodsModelMapper;

    @Autowired
    private BargainOrderModelMapper bargainOrderModelMapper;

    @Autowired
    private BargainRecordModelMapper bargainRecordModelMapper;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private BargainConfigModelMapper bargainConfigModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Override
    public Map<String, Object> index(MainVo vo, String goodsName, Integer status, Integer id) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", vo.getStoreId());
            parmaMap.put("status", status);
            parmaMap.put("product_title", goodsName);
            parmaMap.put("id", id);
            parmaMap.put("pageStart", vo.getPageNo());
            parmaMap.put("pageEnd", vo.getPageSize());
            List<Map<String, Object>> bargainGoodsList = bargainGoodsModelMapper.selectBargainGoodsList(parmaMap);
            int total = bargainGoodsModelMapper.countBargainGoodsList(parmaMap);
            for (Map<String, Object> map : bargainGoodsList) {
                int bargainId = Integer.parseInt(map.get("id").toString());
                int bStatus = Integer.parseInt(map.get("b_status").toString());
                map.put("imgurl", publiceService.getImgPath(map.get("img").toString(), vo.getStoreId()));
                Date startTime = DateUtil.dateFormateToDate(map.get("begin_time").toString(), GloabConst.TimePattern.YMDHMS);
                Date endTime = DateUtil.dateFormateToDate(map.get("end_time").toString(), GloabConst.TimePattern.YMDHMS);
                map.put("attribute_str", GoodsDataUtils.getProductSkuValue(map.get("attribute").toString()));
                BargainGoodsModel bargainGoodsUpdate = new BargainGoodsModel();
                bargainGoodsUpdate.setId(bargainId);
                //活动是否已结束
                if (DateUtil.dateCompare(new Date(), endTime)) {
                    if (bStatus == DictionaryConst.ProductStatus.NOT_OPEN_STATUS || bStatus == DictionaryConst.ProductStatus.PRODUCTSTATUS_SUCCESS_STATUS) {
                        //结束活动
                        bargainGoodsUpdate.setStatus(DictionaryConst.ProductStatus.PRODUCTSTATUS_END_STATUS);
                    } else {
                        bargainGoodsUpdate = null;
                    }
                } else if (DateUtil.dateCompare(new Date(), startTime) && DateUtil.dateCompare(endTime, new Date())) {
                    //开启活动
                    bargainGoodsUpdate.setStatus(DictionaryConst.ProductStatus.PRODUCTSTATUS_SUCCESS_STATUS);
                } else {
                    bargainGoodsUpdate = null;
                }
                if (bargainGoodsUpdate != null) {
                    bargainGoodsModelMapper.updateByPrimaryKeySelective(bargainGoodsUpdate);
                }
            }
            resultMap.put("list", bargainGoodsList);
            resultMap.put("total", total);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取砍价活动商品列表 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "index");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> top(MainVo vo, int id) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            BargainGoodsModel bargainGoodsModel = bargainGoodsModelMapper.selectByPrimaryKey(id);
            if (bargainGoodsModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJBCZ, "数据不存在");
            }
            BargainGoodsModel bargainGoodsUpdate = new BargainGoodsModel();
            bargainGoodsUpdate.setId(id);
            int maxSort = bargainGoodsModelMapper.getMaxSort(vo.getStoreId());
            bargainGoodsUpdate.setSort(maxSort + 1);

            int count = bargainGoodsModelMapper.updateByPrimaryKeySelective(bargainGoodsUpdate);
            if (count < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CZSB, "操作失败");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("置顶 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "top");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> bargainDetail(MainVo vo, int goodsId) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            List<Map<String, Object>> goodsList = bargainGoodsModelMapper.selectBargainGoodsConfigure(vo.getStoreId(), goodsId);
            BargainOrderModel bargainOrderModel = new BargainOrderModel();
            bargainOrderModel.setStore_id(vo.getStoreId());
            bargainOrderModel.setGoods_id(goodsId);
            List<BargainOrderModel> bargainOrderModelList = bargainOrderModelMapper.select(bargainOrderModel);

            resultMap.put("list", goodsList);
            resultMap.put("record", bargainOrderModelList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取活动商品列表 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "bargainDetail");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> del(MainVo vo, String ids) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            List<String> idList = DataUtils.convertToList(ids.split(","));
            if (idList == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_BNWK, "id不能为空");
            }
            Map<String, Object> parmamMap = new HashMap<>(16);
            parmamMap.put("store_id", vo.getStoreId());
            parmamMap.put("bargainList", idList);
            parmamMap.put("begin_time", new Date());
            parmamMap.put("end_time", new Date());
            int count = bargainGoodsModelMapper.countDynamic(parmamMap);
            if (count > 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_BNSCJXZDHD, "不能删除进行中的活动");
            }
            for (String id : idList) {
                BargainGoodsModel bargainGoodsUpdate = new BargainGoodsModel();
                bargainGoodsUpdate.setId(Integer.parseInt(id));
                bargainGoodsUpdate.setIs_delete(1);
                count = bargainGoodsModelMapper.updateByPrimaryKeySelective(bargainGoodsUpdate);
                if (count < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSB, "删除失败");
                }
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除砍价活动 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "del");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> bargainRecordInfo(MainVo vo, Integer barginId, String userName, String type) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            Map<String, Object> parmamMap = new HashMap<>(16);
            parmamMap.put("store_id", vo.getStoreId());
            parmamMap.put("barginId", barginId);
            parmamMap.put("userName", userName);
            parmamMap.put("pageStart", vo.getPageNo());
            parmamMap.put("pageEnd", vo.getPageSize());
            parmamMap.put("addtime_group", "addtime_group");
            if (!StringUtils.isEmpty(type) && !TypeEnum.ALL.equals(type)) {
                List<Integer> bargainList = new ArrayList<>();
                if (TypeEnum.BARGAINING_SUCCESS.toString().equals(type)) {
                    bargainList.add(1);
                    bargainList.add(2);
                } else {
                    bargainList.add(-1);
                }
                parmamMap.put("bargainList", bargainList);
            }

            List<Map<String, Object>> bargainList = bargainOrderModelMapper.getUserBargainInfo(parmamMap);
            for (Map<String, Object> map : bargainList) {
                String orderno = map.get("order_no").toString();
                BargainRecordModel bargainRecordModel = new BargainRecordModel();
                bargainRecordModel.setOrder_no(orderno);
                int count = bargainRecordModelMapper.selectCount(bargainRecordModel);
                BigDecimal bargainMoney = bargainRecordModelMapper.getOrderMoney(vo.getStoreId(), orderno);
                long addtime = Long.parseLong(map.get("addtime").toString());
                map.put("addtime", DateUtil.timeStamp2Date(addtime + "", GloabConst.TimePattern.YMDHM));
                map.put("count", count);
                map.put("bargain_total", bargainMoney);
            }
            resultMap.put("list", bargainList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取砍价记录 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "bargainRecordInfo");
        }
        return resultMap;
    }


    @Override
    public Map<String, Object> bargainHelperInfo(MainVo vo, String orderNo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            List<Map<String, Object>> friendBargainList = bargainRecordModelMapper.getFriendBargainList(vo.getStoreId(), orderNo);
            for (Map<String, Object> map : friendBargainList) {
                long addtime = Long.parseLong(map.get("addtime").toString());
                map.put("addtime", DateUtil.timeStamp2Date(addtime + "", GloabConst.TimePattern.YMDHM));
            }
            resultMap.put("list", friendBargainList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("帮砍详情 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "bargainRecordInfo");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getBargainGoods(MainVo vo, Integer classId, Integer brandId, String title) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", vo.getStoreId());
            parmaMap.put("stockNum", "stockNum");
            parmaMap.put("sort_sort", DataUtils.Sort.DESC.toString());
            parmaMap.put("status_sort", DataUtils.Sort.ASC.toString());
            parmaMap.put("addDate_sort", DataUtils.Sort.DESC.toString());
            parmaMap.put("product_title", title);
            parmaMap.put("bargain", "bargain");
            parmaMap.put("classLeve", classId);
            parmaMap.put("brand_id", brandId);
            parmaMap.put("active", DictionaryConst.GoodsActive.GOODSACTIVE_POSITIVE_KJ);
            List<Map<String, Object>> goodsList = productListModelMapper.getProductListDynamic(parmaMap);
            int total = productListModelMapper.countProductListDynamic(parmaMap);
            for (Map<String, Object> map : goodsList) {
                map.put("pro_img", publiceService.getImgPath(map.get("img").toString(), vo.getStoreId()));
                map.put("attrtype", GoodsDataUtils.getProductSkuValue(map.get("attribute").toString()));
            }
            resultMap.put("product_list", goodsList);
            resultMap.put("total", total);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取砍价商品列表 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getSubGoods");
        }
        return resultMap;
    }


    @Override
    public Map<String, Object> addBargainGoods(AddBargainGoodsVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            if (StringUtils.isEmpty(vo.getObj()) || StringUtils.isEmpty(vo.getStatusData())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            Map<String, Object> parmaMap = JSON.parseObject(vo.getObj(), new TypeReference<Map<String, Object>>() {
            });
            BargainGoodsModel bargainGoodsSave = new BargainGoodsModel();
            bargainGoodsSave.setStore_id(vo.getStoreId());
            bargainGoodsSave.setGoods_id(Integer.parseInt(parmaMap.get("goodsid").toString()));
            bargainGoodsSave.setAttr_id(vo.getAttrid());
            bargainGoodsSave.setMin_price(vo.getMinPrice());
            bargainGoodsSave.setBegin_time(parmaMap.get("startdate").toString());
            bargainGoodsSave.setEnd_time(parmaMap.get("enddate").toString());
            //获取砍价配置信息
            BargainConfigModel bargainConfigModel = new BargainConfigModel();
            bargainConfigModel.setStore_id(vo.getStoreId());
            bargainConfigModel = bargainConfigModelMapper.selectOne(bargainConfigModel);
            int buytime = 0;
            if (bargainConfigModel != null) {
                buytime = bargainConfigModel.getBuy_time();
            }
            bargainGoodsSave.setBuytime(buytime);
            bargainGoodsSave.setMan_num(Integer.parseInt(parmaMap.get("barginman").toString()));
            bargainGoodsSave.setIs_show(Integer.parseInt(parmaMap.get("is_show").toString()));
            bargainGoodsSave.setSort(bargainGoodsModelMapper.getMaxSort(vo.getStoreId()) + 1);
            bargainGoodsSave.setIs_type("");
            bargainGoodsSave.setStatus_data(SerializePhpUtils.JavaSerializeByPhp(vo.getStatusData()));
            bargainGoodsSave.setAddtime(DateUtil.getTime() + "");

            int row = bargainGoodsModelMapper.insertSelective(bargainGoodsSave);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加砍价商品活动 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "addBargainGoods");
        }
        return resultMap;
    }
}

